package com.anlogic.sdk.programfpga.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import com.anlogic.sdk.programfpga.ProgramFPGAModel;
import com.anlogic.sdk.programfpga.ui.ProgramFPGADialog;
import com.anlogic.sdk.programfpga.utils.ProgramFPGAUtils;
import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.ProcLauncherUtils;
import com.anlogic.sdk.utils.UIUtils;

public class ProgramFPGAHandler extends AbstractHandler {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		ProgramFPGADialog dialog = new ProgramFPGADialog(window.getShell());
		int ret = dialog.open();
		if (ret == ProgramFPGADialog.OK) {
			run(dialog.getModel());
		}
		return null;
	}
	
	public void run(ProgramFPGAModel model) {
		String info = ProcLauncherUtils.getHwserverInfo();
		if (info != null) {
			model.setPort(info.split(":")[1]);
		}
		ProgramFPGAUtils.writeScript(model);
		if (model.isLocal() && info == null) {
			if (!EnvUtils.checkOpenocd()) {
				UIUtils.showMessageDialog("ProgramFPGA", "OpenOCD not found! Please check your environment!", MessageDialog.ERROR);
				return;
			}
			ProgramFPGAUtils.programFPGAWithServer(model);
		} else {
			ProgramFPGAUtils.programFPGA(model);
		}
	}
}
